Prisma validator

aliases
No value
tags
prisma/client
description
No value
links
https://www.prisma.io/docs/orm/prisma-client/type-safety/prisma-validator 0180 Prisma 🌈
status
ai response
project
false
area
false
resource
false
title
Prisma validator
created
2025-07-22T16:17:17
updated
2025-07-22T16:24:25

Chat GPT 4.5 answer

PrismaλŠ” 기본적으둜 μƒμ„±λœ Model νƒ€μž…μ„ μ œκ³΅ν•˜μ§€λ§Œ, μ‹€μ œ 쿼리할 λ•Œ μ‚¬μš©ν•˜λŠ” select와 include의 κ²°κ³ΌλŠ” κΈ°λ³Έ λͺ¨λΈ νƒ€μž…κ³Ό λ‹€λ₯΄κ²Œ κ΅¬μ„±λ©λ‹ˆλ‹€. κ·Έλž˜μ„œ κΈ°λ³Έ λͺ¨λΈμ„ 직접 νƒ€μž…μœΌλ‘œ μ‚¬μš©ν•˜λ©΄ 동적 ν•„λ“œλ‚˜ κ΄€κ³„ν˜• ν•„λ“œκ°€ λˆ„λ½λ˜λŠ” λ¬Έμ œκ°€ λ°œμƒν•©λ‹ˆλ‹€.

μ΄λŸ¬ν•œ κ²½μš°λŠ” Prismaκ°€ μ œκ³΅ν•˜λŠ” Prisma.validator 및 νƒ€μž… μœ ν‹Έλ¦¬ν‹°λ₯Ό μ΄μš©ν•΄ ν•΄κ²°ν•˜λŠ” 것이 κ°€μž₯ μ’‹μŠ΅λ‹ˆλ‹€.

βœ… ν•΄κ²° 방법

방법 1. Prisma.validator ν™œμš© (ꢌμž₯ 방식)

import { Prisma } from '@prisma/client';

const userWithPosts = Prisma.validator<Prisma.UserDefaultArgs>()({
  include: { posts: true },
});

type UserWithPosts = Prisma.UserGetPayload<typeof userWithPosts>;

방법 2. μœ ν‹Έλ¦¬ν‹° νƒ€μž… 직접 μ‚¬μš©ν•˜κΈ°

직접 μœ ν‹Έλ¦¬ν‹° νƒ€μž…μ„ μ •μ˜ν•  μˆ˜λ„ μžˆμŠ΅λ‹ˆλ‹€.

import { Prisma } from '@prisma/client';

type UserWithPosts = Prisma.UserGetPayload<{
  include: { posts: true };
}>;

이 방법도 λ™μΌν•œ κ²°κ³Όλ₯Ό μ œκ³΅ν•˜μ§€λ§Œ, νƒ€μž…μ΄ 자주 쓰일 λ•Œ μž¬μ‚¬μš©ν•˜κΈ° μ’‹μŠ΅λ‹ˆλ‹€.


βš™οΈ μ‹€μ „ μ˜ˆμ‹œ

예λ₯Ό λ“€μ–΄ User λͺ¨λΈμ΄ 있고, ν•΄λ‹Ή μœ μ €μ˜ posts와 profile을 ν•¨κ»˜ λ¦¬ν„΄ν•˜λŠ” 경우라면:

import { PrismaClient, Prisma } from '@prisma/client';

const prisma = new PrismaClient();

const userWithDetails = Prisma.validator<Prisma.UserDefaultArgs>()({
  include: { posts: true, profile: true },
});

type UserWithDetails = Prisma.UserGetPayload<typeof userWithDetails>;

async function getUserWithDetails(userId: number): Promise<UserWithDetails | null> {
  return prisma.user.findUnique({
    where: { id: userId },
    include: { posts: true, profile: true },
  });
}

μ΄λ ‡κ²Œ ν•˜λ©΄ UserWithDetailsλŠ” μ •ν™•ν•˜κ²Œ λ‹€μŒκ³Ό 같은 νƒ€μž…μ„ κ°–κ²Œ λ©λ‹ˆλ‹€:

type UserWithDetails = {
  id: number;
  email: string;
  name: string | null;
  posts: Post[];    // posts λͺ¨λΈ λ°°μ—΄ 포함
  profile: Profile | null; // profile λͺ¨λΈ 포함
};

πŸ“Œ μž₯점

이 방법을 적극적으둜 ν™œμš©ν•˜λ©΄ Prisma의 λͺ¨λΈ νƒ€μž… μž¬ν™œμš© μ‹œ νƒ€μž… 정보 손싀 문제λ₯Ό κΉ”λ”ν•˜κ²Œ ν•΄κ²°ν•  수 μžˆμŠ΅λ‹ˆλ‹€.